<template>
  <div class="pdf-container" id="pdfContainer">
    <!-- PDF加载中 -->
    <div v-if="loading" class="pdf-loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>PDF加载中...</span>
    </div>
    
    <!-- PDF渲染区域 -->
    <div v-else class="pdf-content">
      <canvas
        v-for="page in numPages"
        :key="page"
        :id="`pdf-page-${page}`"
        class="pdf-page"
      ></canvas>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, defineComponent } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import * as pdfjsLib from 'pdfjs-dist';
import pdfWorker from 'pdfjs-dist/build/pdf.worker.min.js?url';
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker;

export default defineComponent({
  name: 'PdfViewer',
  
  components: {
    Loading
  },
  
  props: {
    // PDF文件URL
    fileUrl: {
      type: String,
      required: true
    }
  },
  
  emits: ['rendered'],
  
  setup(props, { emit }) {
    // 状态
    const loading = ref(true)
    const numPages = ref(0)
    const pdfDoc = ref(null)
    const pdfPageWidth = ref(0)
    const pdfPageHeight = ref(0)
    const pdfPageOriginWidth = ref([])
    
    /**
     * 加载PDF文档
     */
    const loadPdf = async () => {
      try {
        loading.value = true
        
        // 加载PDF文档
        const loadingTask = pdfjsLib.getDocument(props.fileUrl)
        pdfDoc.value = await loadingTask.promise
        numPages.value = pdfDoc.value.numPages
        
        // 渲染所有页面
        await renderAllPages()
        
        loading.value = false
        
        // 触发渲染完成事件
        emit('rendered', {
          width: pdfPageWidth.value,
          height: pdfPageHeight.value * numPages.value,
          numPages: numPages.value,
          pdfPageOriginWidth: pdfPageOriginWidth.value
        })
      } catch (error) {
        console.error('PDF加载失败:', error)
        loading.value = false
      }
    }
    
    /**
     * 渲染所有页面
     */
    const renderAllPages = async () => {
      const pagePromises = []
      
      for (let i = 1; i <= numPages.value; i++) {
        pagePromises.push(renderPage(i))
      }
      
      await Promise.all(pagePromises)
    }
    
    /**
     * 渲染单个页面
     * @param {Number} pageNum 页码
     */
    const renderPage = async (pageNum) => {
      // 获取页面
      const page = await pdfDoc.value.getPage(pageNum)
      
      // 获取视口
      const viewport = page.getViewport({ scale: 1.5 })
      
      // 获取canvas元素
      const canvas = document.getElementById(`pdf-page-${pageNum}`)
      const context = canvas.getContext('2d')
      
      // 设置canvas尺寸
      canvas.width = viewport.width
      canvas.height = viewport.height
      
      // 保存页面尺寸
      if (pageNum === 1) {
        pdfPageWidth.value = viewport.width
        pdfPageHeight.value = viewport.height
      }
      
      // 保存原始宽度
      pdfPageOriginWidth.value.push({
        page: pageNum,
        width: viewport.width
      })
      
      // 渲染PDF页面
      await page.render({
        canvasContext: context,
        viewport: viewport
      }).promise
    }
    
    // 组件挂载时加载PDF
    onMounted(() => {
      if (props.fileUrl) {
        loadPdf()
      }
    })
    
    return {
      loading,
      numPages
    }
  }
})
</script>

<style lang="scss" scoped>
.pdf-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f5f5;
  
  .pdf-loading {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #409eff;
    
    .loading-icon {
      font-size: 24px;
      margin-bottom: 10px;
      animation: rotate 1s linear infinite;
    }
    
    @keyframes rotate {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  }
  
  .pdf-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    
    .pdf-page {
      margin-bottom: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      background-color: white;
    }
  }
}
</style>